﻿using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.Data;
using System.Drawing;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using System.Windows.Forms;
//using DaChengTcp;
//using DaChengGlobal;
using System.Timers;
using System.Net;
using System.Runtime.InteropServices;
using System.Threading;

namespace ArtificialHeart
{

    unsafe public partial class BoardSetting : Form
    {


        public const byte CMDPARAM_DATA_CORR_INDEX_MAINAD	    = 0xF0;
        public const byte CMDPARAM_DATA_CORR_INDEX_POWERVOLTAGE	= 0xF1;
        public const byte CMDPARAM_DATA_CORR_INDEX_TEMPTURE_0	= 0xF2;
        public const byte CMDPARAM_DATA_CORR_INDEX_TEMPTURE_1   = 0xF3;

        public const byte CMD_SET_ASSIST_FUN_FLAG_ENABLE		= 0x89;
        public const byte CMDPARAM_ASSIST_FUN_DC_POWER_VOLTAGR	= 0;
        public const byte CMDPARAM_ASSIST_FUN_TEMPTURE          = 1;

        public const byte CMDPARAM_BOARD_DESC_FLAG	            = 0x01;
        public const byte CMDPARAM_BOARD_DESC_BASE		        = 0x02;
        public const byte CMDPARAM_BOARD_DESC_PARA		        = 0x04;

        public const byte CMDPARAM_QDECODER_TYPE_MODE	        = 0;
        public const byte CMDPARAM_QDECODER_TYPE_VALUE	        = 1;
        public const byte CMDPARAM_QDECODER_TYPE_RESET          = 2;

        System.Timers.Timer getBoardDescTimer = new System.Timers.Timer();

        private static BoardSetting instance;
        private BoardSetting()
        {
            InitializeComponent();
        }
        public static BoardSetting GetInstance()
        {
            if (instance == null || instance.IsDisposed)
            {
                instance = new BoardSetting();
            }
            return instance;
        }


        private void BoardSetting_Load(object sender, EventArgs e)
        {
            setOutportIndexComboBox.SelectedIndex = 0;
            setOutportValueComboBox.SelectedIndex = 0;
        }

        private void setMainADSigmaButton_Click(object sender, EventArgs e)
        {
            //try
            //{
            //    myTcpClient.SetMainADSigma((float)Convert.ToDouble(setMainADSigmaTextBox.Text));
            //}
            //catch (Exception err)
            //{ MessageBox.Show(err.Message); }
        }
        //void GetHeartBoardConfigThread()
        //{

        //}
        private void getBoardDescriptorButton_Click(object sender, EventArgs e)
        {
            this.BeginInvoke(new MethodInvoker(delegate
            {
                if (Program.mainForm.GetHeartBoardConfig())
                {
                    ArtifiicalGlobal.BoardDesc desc = Program.mainForm.globalDesc;
                    #region 基本
                    inPortEnableTextBox.Text = desc.boardBase.inPortEnable.ToString();
                    outportEnableTextBox.Text = desc.boardBase.outPortEnable.ToString();
                    analogInputTextBox.Text = desc.boardBase.analogInEnable.ToString();
                    baseFlagsTextBox.Text = desc.boardBase.Flags.ToString();
                    sampleFrequencyTextBox.Text = desc.boardBase.sampleFrequery.ToString();
                    sampleBlockpointTextBox.Text = desc.boardBase.blockPoints.ToString();
                    baseReserveTextBox.Text = desc.boardBase.reserve.ToString();
                    mainADSigmaTextBox.Text = desc.boardBase.mainADSigma.ToString();
                    #endregion
                    #region 校正
                    mainADkTextBox.Text = desc.boardPara.mainAD_k.ToString();
                    mainADbTextBox.Text = desc.boardPara.mainAD_b.ToString();



                    assistAD0kTextBox.Text = desc.boardPara.assistAD_k[0].ToString();
                    assistAD1kTextBox.Text = desc.boardPara.assistAD_k[1].ToString();
                    assistAD2kTextBox.Text = desc.boardPara.assistAD_k[2].ToString();
                    assistAD3kTextBox.Text = desc.boardPara.assistAD_k[3].ToString();
                    assistAD4kTextBox.Text = desc.boardPara.assistAD_k[4].ToString();
                    assistAD5kTextBox.Text = desc.boardPara.assistAD_k[5].ToString();
                    assistAD6kTextBox.Text = desc.boardPara.assistAD_k[6].ToString();
                    assistAD7kTextBox.Text = desc.boardPara.assistAD_k[7].ToString();

                    assistAD0bTextBox.Text = desc.boardPara.assistAD_b[0].ToString();
                    assistAD1bTextBox.Text = desc.boardPara.assistAD_b[1].ToString();
                    assistAD2bTextBox.Text = desc.boardPara.assistAD_b[2].ToString();
                    assistAD3bTextBox.Text = desc.boardPara.assistAD_b[3].ToString();
                    assistAD4bTextBox.Text = desc.boardPara.assistAD_b[4].ToString();
                    assistAD5bTextBox.Text = desc.boardPara.assistAD_b[5].ToString();
                    assistAD6bTextBox.Text = desc.boardPara.assistAD_b[6].ToString();
                    assistAD7bTextBox.Text = desc.boardPara.assistAD_b[7].ToString();

                    #endregion
                    MessageBox.Show("获取板卡参数成功。");
                }
                else
                {
                    MessageBox.Show("获取板卡参数失败，请重试。");
                }
            }));
            //Thread thread = new Thread(GetHeartBoardConfigThread);
            //thread.Start();
        }


        private void setAssistADEnableIndexComboBox_SelectedIndexChanged(object sender, EventArgs e)
        {
            setAssistADEnableReflesh();//刷新界面AD使能处
        }

        private void setOutportIndexComboBox_SelectedIndexChanged(object sender, EventArgs e)
        {
            setDOReflesh();
        }

        private void setDataCorrIndexComboBox_SelectedIndexChanged(object sender, EventArgs e)
        {
            setDataCorrReflesh();//刷新界面单独校正参数处
        }
        private void setAssistADEnableReflesh()//刷新界面AD使能处
        {
            //try
            //{
            //    if(setAssistADEnableIndexComboBox.Text == "AD0")
            //    {
            //        if (((boardCfg.boardBaseConfig.analogInEnable) & 0x01)>0)
            //           setAssistADEnableValueComboBox.SelectedIndex = 1;
            //       else
            //           setAssistADEnableValueComboBox.SelectedIndex = 0;
            //    }
            //    else if(setAssistADEnableIndexComboBox.Text == "AD1")
            //    {
            //        if (((boardCfg.boardBaseConfig.analogInEnable) & 0x02) > 0)
            //            setAssistADEnableValueComboBox.SelectedIndex = 1;
            //        else
            //            setAssistADEnableValueComboBox.SelectedIndex = 0;
            //    }
            //    else if(setAssistADEnableIndexComboBox.Text == "AD2")
            //    {
            //        if (((boardCfg.boardBaseConfig.analogInEnable) & 0x04) > 0)
            //            setAssistADEnableValueComboBox.SelectedIndex = 1;
            //        else
            //            setAssistADEnableValueComboBox.SelectedIndex = 0;
            //    }
            //    else if(setAssistADEnableIndexComboBox.Text == "AD3")
            //    {
            //        if (((boardCfg.boardBaseConfig.analogInEnable) & 0x08) > 0)
            //            setAssistADEnableValueComboBox.SelectedIndex = 1;
            //        else
            //            setAssistADEnableValueComboBox.SelectedIndex = 0;
            //    }
            //    else if(setAssistADEnableIndexComboBox.Text == "AD4")
            //    {
            //        if (((boardCfg.boardBaseConfig.analogInEnable) & 0x10) > 0)
            //            setAssistADEnableValueComboBox.SelectedIndex = 1;
            //        else
            //            setAssistADEnableValueComboBox.SelectedIndex = 0;
            //    }
            //    else if(setAssistADEnableIndexComboBox.Text == "AD5")
            //    {
            //        if(((boardCfg.boardBaseConfig.analogInEnable) & 0x20) > 0)
            //            setAssistADEnableValueComboBox.SelectedIndex = 1;
            //        else
            //            setAssistADEnableValueComboBox.SelectedIndex = 0;
            //    }
            //    else if(setAssistADEnableIndexComboBox.Text == "AD6")
            //    {
            //        if(((boardCfg.boardBaseConfig.analogInEnable) & 0x40) > 0)
            //            setAssistADEnableValueComboBox.SelectedIndex = 1;
            //        else
            //            setAssistADEnableValueComboBox.SelectedIndex = 0;
            //    }
            //    else if(setAssistADEnableIndexComboBox.Text == "AD7")
            //    {
            //        if((((boardCfg.boardBaseConfig.analogInEnable) & 0x80) > 0))
            //            setAssistADEnableValueComboBox.SelectedIndex = 1;
            //        else
            //            setAssistADEnableValueComboBox.SelectedIndex = 0;
            //    }
            //}
            //catch (Exception err)
            //{
            //    MessageBox.Show(err.Message);
            //}
        }
        private void setDataCorrReflesh()//刷新界面单独校正参数处
        {
            //try
            //{
            //    boardConfig currentCfg = boardCfg;
            //    if (setDataCorrIndexComboBox.Text == "AD0")
            //    {
            //        setDataCorrKLineEdit.Text = currentCfg.boardParaConfig.assistAD_k[0].ToString();
            //        setDataCorrKLineEdit.Text = currentCfg.boardParaConfig.assistAD_k[0].ToString();
            //        setDataCorrBLineEdit.Text = currentCfg.boardParaConfig.assistAD_b[0].ToString();
            //    }
            //    else if (setDataCorrIndexComboBox.Text == "AD1")
            //    {
            //        setDataCorrKLineEdit.Text = currentCfg.boardParaConfig.assistAD_k[1].ToString();
            //        setDataCorrBLineEdit.Text = currentCfg.boardParaConfig.assistAD_b[1].ToString();
            //    }
            //    else if (setDataCorrIndexComboBox.Text == "AD2")
            //    {
            //        setDataCorrKLineEdit.Text = currentCfg.boardParaConfig.assistAD_k[2].ToString();
            //        setDataCorrBLineEdit.Text = currentCfg.boardParaConfig.assistAD_b[2].ToString();
            //    }
            //    else if (setDataCorrIndexComboBox.Text == "AD3")
            //    {
            //        setDataCorrKLineEdit.Text = currentCfg.boardParaConfig.assistAD_k[3].ToString();
            //        setDataCorrBLineEdit.Text = currentCfg.boardParaConfig.assistAD_b[3].ToString();
            //    }
            //    else if (setDataCorrIndexComboBox.Text == "AD4")
            //    {
            //        setDataCorrKLineEdit.Text = currentCfg.boardParaConfig.assistAD_k[4].ToString();
            //        setDataCorrBLineEdit.Text = currentCfg.boardParaConfig.assistAD_b[4].ToString();
            //    }
            //    else if (setDataCorrIndexComboBox.Text == "AD5")
            //    {
            //        setDataCorrKLineEdit.Text = currentCfg.boardParaConfig.assistAD_k[5].ToString();
            //        setDataCorrBLineEdit.Text = currentCfg.boardParaConfig.assistAD_b[5].ToString();
            //    }
            //    else if (setDataCorrIndexComboBox.Text == "AD6")
            //    {
            //        setDataCorrKLineEdit.Text = currentCfg.boardParaConfig.assistAD_k[6].ToString();
            //        setDataCorrBLineEdit.Text = currentCfg.boardParaConfig.assistAD_b[6].ToString();
            //    }
            //    else if (setDataCorrIndexComboBox.Text == "AD7")
            //    {
            //        setDataCorrKLineEdit.Text = currentCfg.boardParaConfig.assistAD_k[7].ToString();
            //        setDataCorrBLineEdit.Text = currentCfg.boardParaConfig.assistAD_b[7].ToString();
            //    }
            //    else if (setDataCorrIndexComboBox.Text == "MainAD")
            //    {
            //        setDataCorrKLineEdit.Text = currentCfg.boardParaConfig.mainAD_k.ToString();
            //        setDataCorrBLineEdit.Text = currentCfg.boardParaConfig.mainAD_b.ToString();
            //    }
            //    else if (setDataCorrIndexComboBox.Text == "PowerVoltage")
            //    {
            //        setDataCorrKLineEdit.Text = currentCfg.boardParaConfig.powerVoltage_k.ToString();
            //        setDataCorrBLineEdit.Text = currentCfg.boardParaConfig.powerVoltage_b.ToString();
            //    }

            //}
            //catch (Exception err)
            //{
            //    MessageBox.Show(err.Message);
            //}
        }
        private void setDOReflesh()//刷新DO部分
        {
            //try
            //{
            //    boardStatus currentStatus = myTcpClient.GetBoardStatus();
            //    if (setOutportIndexComboBox.Text == "DO0")
            //    {
            //        if (((currentStatus.outPort) & 0x01)>0)
            //            setOutportValueComboBox.SelectedIndex = 1;
            //        else
            //            setOutportValueComboBox.SelectedIndex = 0;
            //    }
            //    else if (setOutportIndexComboBox.Text == "DO1")
            //    {
            //        if (((currentStatus.outPort) & 0x02) > 0)
            //            setOutportValueComboBox.SelectedIndex = 1;
            //        else
            //            setOutportValueComboBox.SelectedIndex = 0;
            //    }
            //    else if (setOutportIndexComboBox.Text == "DO2")
            //    {
            //        if (((currentStatus.outPort) & 0x04) > 0)
            //            setOutportValueComboBox.SelectedIndex = 1;
            //        else
            //            setOutportValueComboBox.SelectedIndex = 0;
            //    }
            //    else if (setOutportIndexComboBox.Text == "DO3")
            //    {
            //        if (((currentStatus.outPort) & 0x08) > 0)
            //            setOutportValueComboBox.SelectedIndex = 1;
            //        else
            //            setOutportValueComboBox.SelectedIndex = 0;
            //    }
            //    else if (setOutportIndexComboBox.Text == "DO4")
            //    {
            //        if (((currentStatus.outPort) & 0x10) > 0)
            //            setOutportValueComboBox.SelectedIndex = 1;
            //        else
            //            setOutportValueComboBox.SelectedIndex = 0;
            //    }
            //    else if (setOutportIndexComboBox.Text == "DO5")
            //    {
            //        if (((currentStatus.outPort) & 0x20) > 0)
            //            setOutportValueComboBox.SelectedIndex = 1;
            //        else
            //            setOutportValueComboBox.SelectedIndex = 0;
            //    }
            //    else if (setOutportIndexComboBox.Text == "DO6")
            //    {
            //        if (((currentStatus.outPort) & 0x40) > 0)
            //            setOutportValueComboBox.SelectedIndex = 1;
            //        else
            //            setOutportValueComboBox.SelectedIndex = 0;
            //    }
            //    else if (setOutportIndexComboBox.Text == "DO7")
            //    {
            //        if (((currentStatus.outPort) & 0x80) > 0)
            //            setOutportValueComboBox.SelectedIndex = 1;
            //        else
            //            setOutportValueComboBox.SelectedIndex = 0;
            //    }
            //}
            //catch (Exception err)
            //{
            //    MessageBox.Show(err.Message);
            //}
        }


        private void setDataCorrectionBtn_Click(object sender, EventArgs e)
        {
            //float k  = float.Parse(setDataCorrKLineEdit.Text);
            //float b = float.Parse(setDataCorrBLineEdit.Text);

            //if (setDataCorrIndexComboBox.SelectedIndex < 8)
            //{
            //    myTcpClient.SetAssistADCorrection((uint)setDataCorrIndexComboBox.SelectedIndex, k, b);
            //}
            //else if (setDataCorrIndexComboBox.Text == "MainAD")
            //{
            //    myTcpClient.SetMainADCorrection(k,b);
            //}
            //else if (setDataCorrIndexComboBox.Text == "PowerVoltage")
            //{
            //    myTcpClient.SetPowerCorrection(k,b);
            //}
            //else if (setDataCorrIndexComboBox.Text == "Temperature0")
            //{
            //    myTcpClient.SetTemperatureCorrection(0,k,b);
            //}
            //else if (setDataCorrIndexComboBox.Text == "Temperature1")
            //{
            //    myTcpClient.SetTemperatureCorrection(1,k,b);
            //}
            //else
            //{
            //    MessageBox.Show("校正参数索引号有误！");
            //}
        }

        private void setMainADBlockpointsBtn_Click(object sender, EventArgs e)
        {
            //try
            //{
            //    myTcpClient.SetADBlockPoint((UInt32)int.Parse(setMainADBlockpointsLineEdit.Text));
            //}
            //catch(Exception err)
            //{
            //    MessageBox.Show(err.Message);

            //}
        }

        private void setMainADResultBuffBtn_Click(object sender, EventArgs e)
        {
            //tCmdSetMainADResultBuff para;
            //para.clearBuff = 0;
            //if (setMainADResultBuffClearBitComboBox.Text == "0")
            //    para.setClearBit = 0;
            //else if (setMainADResultBuffClearBitComboBox.Text == "1")
            //    para.setClearBit = 1;
            //else
            //    para.setClearBit = 2;//除0 1以外的数值。
            //para.reserve = 0;

            //myTcpClient.SetMainADResultBuff(para);
        }

        private void setOutputValueBtn_Click(object sender, EventArgs e)
        {
            try
            {
                ushort status = 0;
                if (setOutportValueComboBox.Text == "OFF")
                {
                    status = 0;
                }
                else if (setOutportValueComboBox.Text == "ON")
                {
                    status = 1;
                }
                else
                {
                    MessageBox.Show("无效的DO状态");
                }
                if (setOutportIndexComboBox.SelectedIndex < 8)
                {
                    SetOutputValueParam((UInt16)setOutportIndexComboBox.SelectedIndex, status);
                }
                else if (setOutportIndexComboBox.Text == "0xFFFF")
                {
                    SetOutputValueParam((UInt16)0xffff, status);
                }
            }
            catch (Exception err)
            {
                MessageBox.Show(err.Message);
            }

        }

        private void setAssistFunFlagEnableBtn_Click(object sender, EventArgs e)
        {
            //try
            //{
            //    bool status = false;

            //    if (setAssistFunFlagEnableValueComboBox.Text == "OFF")
            //        status = false;
            //    else if (setAssistFunFlagEnableValueComboBox.Text == "ON")
            //        status = true;           
            //    else
            //    {
            //        MessageBox.Show("无效的状态");
            //    }

            //    if (setAssistFunFlagEnableFunctionComboBox.Text == "Power")
            //    {
            //        myTcpClient.SetPowerEnable(status);
            //    }
            //    else if (setAssistFunFlagEnableFunctionComboBox.Text == "Temperature")
            //    {
            //        myTcpClient.SetTemperatureEnable(status);
            //    }
            //    else if (setAssistFunFlagEnableFunctionComboBox.Text == "IOResetEncoder")
            //    {
            //        myTcpClient.IOResetEncoderEnable(status);
            //    }
                
            //}
            //catch (Exception err)
            //{
            //    MessageBox.Show(err.Message);

            //}
        }

        private void setMainADGainBtn_Click(object sender, EventArgs e)
        {
            //try
            //{

            //    myTcpClient.SetInstrumentationAmplifierGain((uint)int.Parse(setMainADGianComboBox.Text));

            //}
            //catch (Exception err)
            //{
            //    MessageBox.Show(err.Message);

            //}
            
        }


        private void setAssistADEnableBtn_Click(object sender, EventArgs e)
        {
            //bool status = false;
            //if (setAssistADEnableValueComboBox.Text == "OFF")
            //{
            //    status = false;
            //}
            //else if (setAssistADEnableValueComboBox.Text == "ON")
            //{
            //    status = true;
            //}
            //myTcpClient.SetAssistADEnable((UInt16)setAssistADEnableIndexComboBox.SelectedIndex, status);
        }

        private void setQdecoderBtn_Click(object sender, EventArgs e)
        {
            //tCmdSetQdecoderParam para;
            //para.type = 0;
            //para.value = 0;
            //para.index = (UInt16)int.Parse(setQdecoderIndexComboBox.Text);
            //if(setQdecoderTypeComboBox.Text == "MODE")
            //    para.type = CMDPARAM_QDECODER_TYPE_MODE;
            //else     if(setQdecoderTypeComboBox.Text == "VALUE")
            //    para.type = CMDPARAM_QDECODER_TYPE_VALUE;
            //else     if(setQdecoderTypeComboBox.Text == "RESET")
            //    para.type = CMDPARAM_QDECODER_TYPE_RESET;

            //if (setQdecoderValueComboBox.Text == "PhaseEncode:0")
            //    para.value = 0;
            //else if (setQdecoderValueComboBox.Text == "CountAndDir:1")
            //    para.value = 1;
            //else
            //    para.value = int.Parse(setQdecoderValueComboBox.Text);
            //myTcpClient.SetQdecoderParam(para);
        }

        private void tabControl_SelectedIndexChanged(object sender, EventArgs e)
        {
            //if (tabControl.SelectedIndex == 1)
            //{
            //    baseCheckBox.Checked = true;
            //    correctionCheckBox.Checked = false;
            //}
            //else if (tabControl.SelectedIndex == 2)
            //{
            //    baseCheckBox.Checked = false;
            //    correctionCheckBox.Checked = true;
            //}
            //else
            //{
            //    baseCheckBox.Checked = false;
            //    correctionCheckBox.Checked = false;
            //}
        }

        private void setBoardDescritorBtn_Click(object sender, EventArgs e)
        {
            try
            {
                ArtifiicalGlobal.BoardDesc boardDesc = new ArtifiicalGlobal.BoardDesc();
                boardDesc.boardBase.inPortEnable = (UInt16)int.Parse(inPortEnableTextBox.Text);
                boardDesc.boardBase.outPortEnable = (UInt16)int.Parse(outportEnableTextBox.Text);
                boardDesc.boardBase.analogInEnable = (UInt16)int.Parse(analogInputTextBox.Text);
                boardDesc.boardBase.Flags = (UInt16)int.Parse(baseFlagsTextBox.Text);
                boardDesc.boardBase.sampleFrequery = (UInt32)int.Parse(sampleFrequencyTextBox.Text);
                boardDesc.boardBase.blockPoints = (UInt32)int.Parse(sampleBlockpointTextBox.Text);
                boardDesc.boardBase.reserve = (UInt32)int.Parse(baseReserveTextBox.Text);
                boardDesc.boardBase.mainADSigma = float.Parse(mainADSigmaTextBox.Text);
                boardDesc.boardPara.mainAD_k = float.Parse(mainADkTextBox.Text);
                boardDesc.boardPara.mainAD_b = float.Parse(mainADbTextBox.Text);
                boardDesc.boardPara.assistAD_k[0] = float.Parse(assistAD0kTextBox.Text);
                boardDesc.boardPara.assistAD_k[1] = float.Parse(assistAD1kTextBox.Text);
                boardDesc.boardPara.assistAD_k[2] = float.Parse(assistAD2kTextBox.Text);
                boardDesc.boardPara.assistAD_k[3] = float.Parse(assistAD3kTextBox.Text);
                boardDesc.boardPara.assistAD_k[4] = float.Parse(assistAD4kTextBox.Text);
                boardDesc.boardPara.assistAD_k[5] = float.Parse(assistAD5kTextBox.Text);
                boardDesc.boardPara.assistAD_k[6] = float.Parse(assistAD6kTextBox.Text);
                boardDesc.boardPara.assistAD_k[7] = float.Parse(assistAD7kTextBox.Text);
                boardDesc.boardPara.assistAD_b[0] = float.Parse(assistAD0bTextBox.Text);
                boardDesc.boardPara.assistAD_b[1] = float.Parse(assistAD1bTextBox.Text);
                boardDesc.boardPara.assistAD_b[2] = float.Parse(assistAD2bTextBox.Text);
                boardDesc.boardPara.assistAD_b[3] = float.Parse(assistAD3bTextBox.Text);
                boardDesc.boardPara.assistAD_b[4] = float.Parse(assistAD4bTextBox.Text);
                boardDesc.boardPara.assistAD_b[5] = float.Parse(assistAD5bTextBox.Text);
                boardDesc.boardPara.assistAD_b[6] = float.Parse(assistAD6bTextBox.Text);
                boardDesc.boardPara.assistAD_b[7] = float.Parse(assistAD7bTextBox.Text);


                ArtifiicalGlobal.UsbPrefix prefix = new ArtifiicalGlobal.UsbPrefix();
                prefix.addr = ArtifiicalGlobal.ARTIFICIAL_BOARD_ADDR;
                prefix.funcCode = ArtifiicalGlobal.CMD_SET_BOARD_PARAMS_DESCRIPTOR_TO_BOARD;
                prefix.length = (UInt16)(Marshal.SizeOf(boardDesc) + Marshal.SizeOf(prefix));
                byte[] byteToWrite = ArtifiicalGlobal.MergeByte(ArtifiicalGlobal.StructToBytes(prefix, Marshal.SizeOf(prefix)), ArtifiicalGlobal.StructToBytes(boardDesc, Marshal.SizeOf(boardDesc)));
                Program.mainForm.virtualComlPort.Write(byteToWrite, 0, byteToWrite.Length); 
            }
            catch (Exception exc)
            {
                MessageBox.Show(exc.Message);
            }
        }

        private void loadDescFromEEPROMBtn_Click(object sender, EventArgs e)
        {

            try
            {
                ArtifiicalGlobal.UsbPrefix prefix = new ArtifiicalGlobal.UsbPrefix();
                prefix.addr = ArtifiicalGlobal.ARTIFICIAL_BOARD_ADDR;
                prefix.funcCode = ArtifiicalGlobal.CMD_SET_BOARD_PARAMS_DESCRIPTOR_FROM_EEP;
                prefix.length = (UInt16)(Marshal.SizeOf(prefix));
                byte[] byteToWrite = ArtifiicalGlobal.StructToBytes(prefix, Marshal.SizeOf(prefix));
                Program.mainForm.virtualComlPort.Write(byteToWrite, 0, byteToWrite.Length);
            }
            catch (Exception exc)
            {
                MessageBox.Show(exc.Message);
            }
        }

        private void saveDescToEEPROMBtn_Click(object sender, EventArgs e)
        {
            try
            {
                ArtifiicalGlobal.UsbPrefix prefix = new ArtifiicalGlobal.UsbPrefix();
                prefix.addr = ArtifiicalGlobal.ARTIFICIAL_BOARD_ADDR;
                prefix.funcCode = ArtifiicalGlobal.CMD_SET_BOARD_PARAMS_DESCRIPTOR_TO_EEP;
                prefix.length = (UInt16)(Marshal.SizeOf(prefix));
                byte[] byteToWrite = ArtifiicalGlobal.StructToBytes(prefix, Marshal.SizeOf(prefix));
                Program.mainForm.virtualComlPort.Write(byteToWrite, 0, byteToWrite.Length);
            }
            catch (Exception exc)
            {
                MessageBox.Show(exc.Message);
            }
        }

        private void setEncoderNumberBtn_Click(object sender, EventArgs e)
        {
            //myTcpClient.SetEncoderValue((uint)encoderIndexComboBox.SelectedIndex, int.Parse(encoderNumberTextBox.Text));

        }

        private void SetOutputValueParam(UInt16 index, UInt16 value)
        {
            ArtifiicalGlobal.cmdSetOutportValueParam cmd = new ArtifiicalGlobal.cmdSetOutportValueParam();
            ArtifiicalGlobal.UsbPrefix prefix = new ArtifiicalGlobal.UsbPrefix();
            prefix.addr = ArtifiicalGlobal.ARTIFICIAL_BOARD_ADDR;
            prefix.funcCode = ArtifiicalGlobal.CMD_SET_OUTPORT_VALUE;
            prefix.length = (UInt16)(Marshal.SizeOf(cmd) + Marshal.SizeOf(prefix));
            cmd.index = index; cmd.value = value;
            byte[] byteToWrite = ArtifiicalGlobal.MergeByte(ArtifiicalGlobal.StructToBytes(prefix, Marshal.SizeOf(prefix)), ArtifiicalGlobal.StructToBytes(cmd, Marshal.SizeOf(cmd)));
            Program.mainForm.virtualComlPort.Write(byteToWrite, 0, byteToWrite.Length);
        }

        private void buttonClearAlarm_Click(object sender, EventArgs e)
        {
            try
            {
                ArtifiicalGlobal.cmdSetOutportValueParam cmd = new ArtifiicalGlobal.cmdSetOutportValueParam();
                ArtifiicalGlobal.UsbPrefix prefix = new ArtifiicalGlobal.UsbPrefix();
                prefix.addr = ArtifiicalGlobal.ARTIFICIAL_BOARD_ADDR;
                prefix.funcCode = ArtifiicalGlobal.CMD_SET_SERVO_ON_ALM_CLR;
                prefix.length = (UInt16)(Marshal.SizeOf(cmd) + Marshal.SizeOf(prefix));
                cmd.index = 1; cmd.value = 1;
                byte[] byteToWrite = ArtifiicalGlobal.MergeByte(ArtifiicalGlobal.StructToBytes(prefix, Marshal.SizeOf(prefix)), ArtifiicalGlobal.StructToBytes(cmd, Marshal.SizeOf(cmd)));
                Program.mainForm.virtualComlPort.Write(byteToWrite, 0, byteToWrite.Length);
            }
            catch (Exception exc)
            {
                MessageBox.Show(exc.Message);
            }
        }

        private void buttonServoOn_Click(object sender, EventArgs e)
        {
            try
            {
                ArtifiicalGlobal.cmdSetOutportValueParam cmd = new ArtifiicalGlobal.cmdSetOutportValueParam();
                ArtifiicalGlobal.UsbPrefix prefix = new ArtifiicalGlobal.UsbPrefix();
                prefix.addr = ArtifiicalGlobal.ARTIFICIAL_BOARD_ADDR;
                prefix.funcCode = ArtifiicalGlobal.CMD_SET_SERVO_ON_ALM_CLR;
                prefix.length = (UInt16)(Marshal.SizeOf(cmd) + Marshal.SizeOf(prefix));
                cmd.index = 0; cmd.value = 1;
                byte[] byteToWrite = ArtifiicalGlobal.MergeByte(ArtifiicalGlobal.StructToBytes(prefix, Marshal.SizeOf(prefix)), ArtifiicalGlobal.StructToBytes(cmd, Marshal.SizeOf(cmd)));
                Program.mainForm.virtualComlPort.Write(byteToWrite, 0, byteToWrite.Length);
            }
            catch (Exception exc)
            {
                MessageBox.Show(exc.Message);
            }
        }

        private void buttonServoOff_Click(object sender, EventArgs e)
        {
            try
            {
                ArtifiicalGlobal.cmdSetOutportValueParam cmd = new ArtifiicalGlobal.cmdSetOutportValueParam();
                ArtifiicalGlobal.UsbPrefix prefix = new ArtifiicalGlobal.UsbPrefix();
                prefix.addr = ArtifiicalGlobal.ARTIFICIAL_BOARD_ADDR;
                prefix.funcCode = ArtifiicalGlobal.CMD_SET_SERVO_ON_ALM_CLR;
                prefix.length = (UInt16)(Marshal.SizeOf(cmd) + Marshal.SizeOf(prefix));
                cmd.index = 0; cmd.value = 0;
                byte[] byteToWrite = ArtifiicalGlobal.MergeByte(ArtifiicalGlobal.StructToBytes(prefix, Marshal.SizeOf(prefix)), ArtifiicalGlobal.StructToBytes(cmd, Marshal.SizeOf(cmd)));
                Program.mainForm.virtualComlPort.Write(byteToWrite, 0, byteToWrite.Length);
            }
            catch (Exception exc)
            {
                MessageBox.Show(exc.Message);
            }
        }

        private void buttonStartMotion_Click(object sender, EventArgs e)
        {
            try
            {
                ArtifiicalGlobal.UsbPrefix prefix = new ArtifiicalGlobal.UsbPrefix();
                prefix.addr = ArtifiicalGlobal.ARTIFICIAL_BOARD_ADDR;
                prefix.funcCode = ArtifiicalGlobal.CMD_RETURN_MOTOR_STATUS;
                prefix.length = (UInt16)(Marshal.SizeOf(prefix));
                byte[] byteToWrite = ArtifiicalGlobal.StructToBytes(prefix, Marshal.SizeOf(prefix));
                Program.mainForm.virtualComlPort.Write(byteToWrite, 0, byteToWrite.Length);

                Program.mainForm.globalState = 255;
                for (int i = 500; i > 0; i--)
                {
                    if (Program.mainForm.globalState != 0xff) break;
                    Thread.Sleep(1);
                }

            }
            catch (Exception exc)
            {
                MessageBox.Show(exc.Message);
            }

            try
            {
                if (Program.mainForm.globalState != 0)
                {
                    MessageBox.Show("电机状态有冲突，请重试");
                }
                else
                {
                    if (Int32.Parse(textBoxAccelerate.Text) < 0)
                    { MessageBox.Show("加速度不能为负"); return; }
                    if (Int32.Parse(textBoxDecelerate.Text) < 0)
                    { MessageBox.Show("减速度不能为负"); return; }

                    if (Int32.Parse(textBoxSpeed.Text) < 0)
                    { MessageBox.Show("速度不能为负"); return; }

                    ArtifiicalGlobal.cmdSetMotorParam cmd = new ArtifiicalGlobal.cmdSetMotorParam();
                    ArtifiicalGlobal.UsbPrefix prefix = new ArtifiicalGlobal.UsbPrefix();
                    prefix.addr = ArtifiicalGlobal.ARTIFICIAL_BOARD_ADDR;
                    prefix.funcCode = ArtifiicalGlobal.CMD_SET_MOTOR_PARAM;
                    prefix.length = (UInt16)(Marshal.SizeOf(cmd) + Marshal.SizeOf(prefix)+2);
                    cmd.acce = Int32.Parse(textBoxAccelerate.Text);
                    cmd.dece = Int32.Parse(textBoxDecelerate.Text);
                    cmd.speed = Int32.Parse(textBoxSpeed.Text);
                    cmd.position = Int32.Parse(textBoxPosition.Text);
                    byte[] byteToWrite = ArtifiicalGlobal.MergeByte(ArtifiicalGlobal.StructToBytes(prefix, Marshal.SizeOf(prefix)), ArtifiicalGlobal.StructToBytes(cmd, Marshal.SizeOf(cmd)));
                    short crc = (short)CRC16.calcCrc16(byteToWrite, Marshal.SizeOf(prefix), byteToWrite.Length - Marshal.SizeOf(prefix));
                    byte[] byteCRC = BitConverter.GetBytes(crc);
                    Program.mainForm.virtualComlPort.Write(byteToWrite, 0, byteToWrite.Length);
                    Program.mainForm.virtualComlPort.Write(byteCRC, 0, byteCRC.Length);
                    //
                    //MessageBox.Show("电机就绪");
                }
            }
            catch (Exception exc)
            {
                MessageBox.Show(exc.Message);
            }
        }

    }
}
